package com.icesoft.core.dao.criteria;

import lombok.Getter;

import java.util.List;

@Getter
public class QuerySupport {

    private Class<?> fromTable;
    private String hql;
    private List<AndPropertyFilter.Property> propertys;
    private int offset;
    private int limit;
    private String str;
    boolean countQuery;

    private SelectBuilder selectBuilder;
    private FromBuilder fromBuilder;

    public QuerySupport(SelectBuilder selectBuilder) {
        this.selectBuilder = selectBuilder;
        this.fromBuilder = selectBuilder.fromBuilder;
        this.countQuery = selectBuilder.isCount;
        this.fromTable = fromBuilder.fromTable;
    }

    @Override
    public String toString() {
        return getStr();
    }

    public String getStr() {
        if (str == null) {
            build();
        }
        return str;
    }

    public String getHql() {
        if (hql == null) {
            build();
        }
        return hql;
    }

    public void build() {
        if (fromBuilder.limitBuilder != null) {
            this.offset = fromBuilder.limitBuilder.offset;
            this.limit = fromBuilder.limitBuilder.limit;
        }
        String select = selectBuilder.getHql();
        StringBuilder hql = new StringBuilder(" ").append(fromBuilder.getFromHql());
        if (fromBuilder.whereBuilder != null) {
            this.propertys = fromBuilder.whereBuilder.getPropertys();
            hql.append(" ").append(fromBuilder.whereBuilder.getHql());
        }
        if (fromBuilder.groupByBuilder != null) {
            hql.append(" ").append(fromBuilder.groupByBuilder.getHql());
        }
        if (!this.countQuery && fromBuilder.orderBuilder != null) {
            hql.append(" ").append(fromBuilder.orderBuilder.getHql());
        }
        this.hql = select + hql.toString();
        if (selectBuilder.isCount) {
            this.offset = 0;
            this.limit = 1;
        }

        hql = new StringBuilder(" ").append(fromBuilder.getFromHql());
        if (fromBuilder.whereBuilder != null) {
            hql.append(" ").append(fromBuilder.whereBuilder.toString());
        }
        if (fromBuilder.groupByBuilder != null) {
            hql.append(" ").append(fromBuilder.groupByBuilder.toString());
        }
        if (!this.countQuery && fromBuilder.orderBuilder != null) {
            hql.append(" ").append(fromBuilder.orderBuilder.toString());
        }

        this.str = select + hql.toString();
        if (!selectBuilder.isCount && fromBuilder.limitBuilder != null) {
            this.str = this.str + " " + fromBuilder.limitBuilder.toString();
        }
    }

}
